# GIL 详见大纲

# 互斥锁

# 1. GIL 自动上锁解锁, 文件中的互斥锁Lock 手动上锁解锁.
# 2. GIL锁 保护解释器的数据安全. 文件的互斥锁Lock 保护的文件数据的安全.

# from threading import Thread
# from threading import Lock
# import time
#
# lock = Lock()
# x = 100
#
# def task():
#     global x
#     lock.acquire()
#     temp = x
#     # time.sleep(1)
#     temp -= 1
#     x = temp
#     lock.release()
#
#
#
# if __name__ == '__main__':
#     t_l = []
#     for i in range(100):
#         t = Thread(target=task)
#         t_l.append(t)
#         t.start()
#
#     for i in t_l:
#         i.join()
#
#     print(f'主线程{x}')
#
# # 线程全部是计算密集型:当程序执行,开启100个线程时,第一个线程先要拿到GIL锁,然后拿到lock锁,释放lock锁,最后释放GIL锁.



from threading import Thread
from threading import Lock
import time

lock = Lock()
x = 100

def task():
    global x
    lock.acquire()
    temp = x
    time.sleep(1)
    temp -= 1
    x = temp
    lock.release()



if __name__ == '__main__':
    t_l = []
    for i in range(100):
        t = Thread(target=task)
        t_l.append(t)
        t.start()

    for i in t_l:
        i.join()

    print(f'主线程{x}')
'''
线程IO密集型:当程序执行,开启100个线程时,第一个线程先要拿到GIL锁,然后拿到lock锁,
运行,遇到....截图上有解释..

总结: 自己加互斥锁,一定要加在处理共享数据的地方,加的范围不要扩大,

'''
# 释放lock锁,最后释放GIL锁.